<template>
  <div class="main-con">
    <div class="header">
      <el-button type="success" @click="handleClassify()">新增分类</el-button>
    </div>
    <el-table
      :data="tableData"
      v-loading="loading"
      element-loading-text="加载中"
      style="width: 100%; margin-top: 20px"
      border
    >
      <el-table-column prop="name" label="分类名称" align="center" />
      <el-table-column prop="sort" label="排序" align="center" />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <button-table type="edit" @click="handleClassify(scope.row)" />
          <el-popconfirm title="确定删除吗？" @confirm="del(scope.row)">
            <template #reference>
              <button-table type="delete" @click.stop="() => {}" />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="visible"
      :title="(selectClassifyId ? '编辑' : '新增') + '分类'"
      width="500px"
      @closed="onClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="userRules"
        label-width="100px"
        @keyup.enter="addForm_enter(formRef)"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            :min="0"
            controls-position="right"
            placeholder="请输入排序"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="addForm_enter(formRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onBeforeMount } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { ContentService, ClassifyItem } from '@/api/contentApi'

  const loading = ref(false)
  const formRef = ref<FormInstance | null>(null)
  const selectClassifyId = ref('')
  const tableData = ref<ClassifyItem[]>([])
  const visible = ref(false)
  const submitLoading = ref(false)
  const formData = ref({
    name: '',
    sort: 0
  })

  const userRules = ref({
    name: [{ required: true, message: '请输入分类名', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
  })

  onBeforeMount(() => {
    getTableData()
  })

  const getTableData = async () => {
    loading.value = true
    try {
      const response = await ContentService.classifyQuery({ page: 1, pageSize: 10 })
      if (response.code === '200' && response.data) {
        tableData.value = response.data.list || []
      } else {
        console.error('获取分类列表失败:', response.message || '未知错误')
        ElMessage.error(response.message || '获取分类列表失败')
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
      ElMessage.error('获取分类列表失败')
    } finally {
      loading.value = false
    }
  }

  const handleClassify = (item: ClassifyItem = {} as ClassifyItem) => {
    selectClassifyId.value = item.recommendTypeId || ''
    formData.value = { ...item }
    visible.value = true
  }

  const del = async (row: ClassifyItem) => {
    if (!row.recommendTypeId) return

    try {
      await ContentService.classifyDelete({ recommendTypeId: row.recommendTypeId })
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    } catch (error) {
      console.error('删除分类失败:', error)
    }
  }

  const addForm_enter = (formEl: FormInstance | null) => {
    if (!formEl) return

    formEl.validate((valid) => {
      if (valid) {
        submitForm()
      }
    })
  }

  const submitForm = async () => {
    submitLoading.value = true
    try {
      if (selectClassifyId.value) {
        // 编辑
        await ContentService.classifyEdit({
          recommendTypeId: selectClassifyId.value,
          ...formData.value
        })
      } else {
        // 新增
        await ContentService.classifyAdd(formData.value)
      }

      visible.value = false
      ElMessage({
        message: `${selectClassifyId.value ? '修改' : '新增'}成功`,
        type: 'success'
      })
      selectClassifyId.value = ''
      getTableData()
    } catch (error) {
      console.error('保存分类失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  const onClosed = () => {
    formRef.value?.resetFields()
  }
</script>

<style scoped lang="scss">
  .main-con {
    padding: 20px;
    margin-top: 20px;
    overflow: hidden;
    background: var(--art-bg-color);
  }
</style>
